﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using filmquiz.Src.Domain;
using filmquiz.Src.Login;
using filmquiz.Src.SessionHandle;
using filmquiz.Src.Mail;
using filmquiz.Src.DatabaseAccess;

public partial class MasterPage : System.Web.UI.MasterPage
{
    private LoginController loginController = new LoginController();
    private SessionController sessionController = new SessionController();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["image"] == null)
        {
            Session["image"] = 1;
        }
        if (Session["loggedIn"] == null)
        {
            Session["loggedIn"] = false;
        }

        if (!(bool)Session["loggedIn"] && Request.Cookies["username"] != null)
        {
            if(loginController.DoLoginFromCookie((string)Request.Cookies["username"].Value, int.Parse((string)Request.Cookies["id"].Value), Session))
            {
                User user = loginController.getLoggedInUser();
                sessionController.updateSession(user, Session);
                CookieHelper.getInstance().createLoginCookies(user, Response);
            }
        }
    }

    private void Page_PreRender(object sender, System.EventArgs e)
    {
        renderLoginBox();
        renderRegisterButton();
    }

    protected void LoginButton_Click(object sender, EventArgs e)
    {
        
        User user = sessionController.LoginUser(userTxt.Text, passTxt.Text, Session);
        CookieHelper.getInstance().createLoginCookies(user, Response);
    }

    protected void LogoutButton_Click(object sender, EventArgs e)
    {
        sessionController.logoutUser(Session);
        CookieHelper.getInstance().deleteLoginCookies(Request, Response);
    }

    private void renderRegisterButton()
    {
        if ((bool)Session["loggedIn"])
        {
            registerLabel.Text = "Rediger bruger";
        }
    }

    private void renderLoginBox()
    {
        if (Session["loggedIn"] == null)
        {
            Session["loggedIn"] = false;
        }
        if ((Boolean)Session["loggedIn"])
        {
            logginIn.Visible = false;
            loggedIn.Visible = true;

            brugernavn.Text = ((User)Session["user"]).getName();
        }
        else
        {
            logginIn.Visible = true;
            loggedIn.Visible = false;
        }
    }

    protected void forgotPasswordBtn_Click(object sender, EventArgs e)
    {
        UserHelper.getInstance().sendNewPassword(forgotPasswordTxt.Text);
    }
}